package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.zyyoona7.popup.EasyPopup;
import com.zyyoona7.popup.XGravity;
import com.zyyoona7.popup.YGravity;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.AddDataAdapter;
import flc.ast.adapter.DocumentsAdapter;
import flc.ast.databinding.ActivityPhoneMemoryBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.media.MediaInfo;
import stark.common.basic.utils.MimeUtils;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.view.StkTextView;
import stark.common.basic.view.container.StkRecycleView;

public class PhoneMemoryActivity extends BaseAc<ActivityPhoneMemoryBinding> {

    private List<MediaInfo> mMediaBeanList = new ArrayList<>();
    private DocumentsAdapter mDocumentsAdapter;
    private String mCurrentRootPath, mSelPath;
    private Dialog myMoreDialog, myInfoDialog, myRenameDialog, myAddDialog, mySortDialog;
    private EditText editRenameText, editAddText;
    private EasyPopup mCirclePop;
    private int pos;


    @Override
    protected int onCreate() {
        return R.layout.activity_phone_memory;
    }

    @Override
    public void onBackPressed() {
        if (mCurrentRootPath.equals(Environment.getExternalStorageDirectory().getPath())) {
            super.onBackPressed();
        } else {
            mCurrentRootPath = FileUtils.getDirName(mCurrentRootPath);
            mCurrentRootPath = mCurrentRootPath.substring(0, mCurrentRootPath.length() - 1);
            getMoveData(mCurrentRootPath);
        }
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivPhoneMemoryBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivHome.setOnClickListener(this);
        mDataBinding.ivCopy.setOnClickListener(this);
        mDataBinding.ivMore.setOnClickListener(this);

        mDataBinding.rvFile.setLayoutManager(new LinearLayoutManager(mContext));
        mDocumentsAdapter = new DocumentsAdapter();
        mDataBinding.rvFile.setAdapter(mDocumentsAdapter);
        mDocumentsAdapter.addChildClickViewIds(R.id.llDocuments, R.id.ivDocumentsDetails);
        mDocumentsAdapter.setOnItemChildClickListener(this);

        //重命名弹框
        renameDialog();
        //添加文件夹弹框
        addDialog();
        //排序弹框
        sortDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivHome://返回最外层文件夹
                mCurrentRootPath = Environment.getExternalStorageDirectory().getPath();
                getMoveData(mCurrentRootPath);
                break;
            case R.id.ivCopy://粘贴
                copy();
                break;
            case R.id.ivMore://更多
                initPopMenu();
                mCirclePop.showAtAnchorView(v, YGravity.BELOW, XGravity.ALIGN_RIGHT, 0, 0);
                break;
            //更多弹框
            case R.id.tvDialogMoreCopy://复制
                myMoreDialog.dismiss();
                SPUtils.getInstance().put(Content.copy_file, mSelPath);
                ToastUtils.showShort(R.string.have_copy);
                mDataBinding.ivCopy.setVisibility(View.VISIBLE);
                break;
            case R.id.tvDialogMoreInfo://信息
                myMoreDialog.dismiss();
                infoDialog();
                myInfoDialog.show();
                break;
            case R.id.tvDialogMoreRename://重命名
                myMoreDialog.dismiss();
                myRenameDialog.show();
                break;
            case R.id.tvDialogMoreDelete://删除
                myMoreDialog.dismiss();
                delete();
                break;
            //重命名
            case R.id.tvDialogRenameConfirm:
                String name = editRenameText.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    ToastUtils.showShort(getText(R.string.please_input_video_name));
                    return;
                }
                FileUtils.rename(mSelPath, name + "." + FileUtils.getFileExtension(mSelPath));
                myRenameDialog.dismiss();
                editRenameText.setText("");
                getMoveData(mCurrentRootPath);
                break;
            case R.id.tvDialogRenameCancel:
                editRenameText.setText("");
                myRenameDialog.dismiss();
                break;
            //添加文件夹
            case R.id.tvDialogAddConfirm:
                String name1 = editAddText.getText().toString();
                if (TextUtils.isEmpty(name1)) {
                    ToastUtils.showShort(getText(R.string.please_input_video_name));
                    return;
                }
                File file = new File(mCurrentRootPath, name1);
                if (!file.exists()) {
                    boolean mkdirs = file.mkdirs();
                    if (mkdirs) {
                        ToastUtils.showShort(R.string.add_file_s);
                        mDocumentsAdapter.notifyDataSetChanged();
                    } else {
                        ToastUtils.showShort(R.string.add_file_s);
                    }
                } else {
                    ToastUtils.showShort(R.string.is_file);
                }
                editRenameText.setText("");
                myAddDialog.dismiss();
                break;
            case R.id.tvDialogAddCancel:
                editAddText.setText("");
                myAddDialog.dismiss();
                break;
            //排序弹框
            case R.id.tvDialogSortName://按名称排序
                mySortDialog.dismiss();
                sortByName(mDocumentsAdapter.getData());
                break;
            case R.id.tvDialogSortTime://按时间排序
                mySortDialog.dismiss();
                sortByDate(mDocumentsAdapter.getData());
                break;
            case R.id.tvDialogSortSize://按大小排序
                mySortDialog.dismiss();
                sortBySize(mDocumentsAdapter.getData());
                break;
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.llDocuments:
                mCurrentRootPath = mDocumentsAdapter.getItem(position).getPath();
                if (FileUtils.isDir(mCurrentRootPath)) {
                    getMoveData(mCurrentRootPath);
                }
                break;
            case R.id.ivDocumentsDetails:
                mSelPath = mDocumentsAdapter.getItem(position).getPath();
                //更多弹框
                moreDialog();
                myMoreDialog.show();
                break;
        }
    }

    @Override
    protected void initData() {
        mCurrentRootPath = Environment.getExternalStorageDirectory().getPath();
        getMoveData(mCurrentRootPath);
    }

    private void getMoveData(String rootPath) {
        mDataBinding.ivCopy.setVisibility(TextUtils.isEmpty(SPUtils.getInstance().getString(Content.copy_file)) ? View.GONE : View.VISIBLE);
        mDataBinding.tvMoveAddress.setText(rootPath);
        List<File> files = FileUtils.listFilesInDir(rootPath);
        if (files.size() == 0) {
            mDataBinding.ivNoData.setVisibility(View.VISIBLE);
            mDataBinding.rvFile.setVisibility(View.GONE);
        } else {
            mDataBinding.ivNoData.setVisibility(View.GONE);
            mDataBinding.rvFile.setVisibility(View.VISIBLE);
            mMediaBeanList.clear();
            for (File file : files) {
                mMediaBeanList.add(new MediaInfo(file.getPath(), file.getName(), file.length(),
                        FileUtils.getFileLastModified(file) / 1000L, null, null));
            }
            mDataBinding.rvFile.scrollToPosition(0);
            mDocumentsAdapter.setList(mMediaBeanList);
        }
    }

    private void copy() {
        File sourceFile = new File(SPUtils.getInstance().getString(Content.copy_file));
        File destinationFolder = new File(mCurrentRootPath);
        // 如果目标文件夹不存在，则创建它
        if (!destinationFolder.exists()) {
            destinationFolder.mkdirs();
        }
        // 构造目标文件路径
        File destinationFile = new File(destinationFolder.getPath() + File.separator + sourceFile.getName());
        FileUtils.copy(sourceFile, destinationFile);
        ToastUtils.showShort(R.string.copy_suc);
        SPUtils.getInstance().remove(Content.copy_file);
        getMoveData(mCurrentRootPath);
    }

    private void delete() {
        showDialog(getString(R.string.delete_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        FileUtils.delete(mSelPath);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        getMoveData(mCurrentRootPath);
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.delete_suc));
                    }
                });
            }
        }, 1000);
    }

    // 根据文件名称排序
    public void sortByName(List<MediaInfo> mMediaBeanList) {
        pos = 0;
        Collections.sort(mMediaBeanList, new Comparator<MediaInfo>() {
            @Override
            public int compare(MediaInfo file1, MediaInfo file2) {
                return file1.getName().compareToIgnoreCase(file2.getName());
            }
        });
        mDocumentsAdapter.notifyDataSetChanged();
    }

    // 根据文件日期排序
    public void sortByDate(List<MediaInfo> mMediaBeanList) {
        pos = 1;
        Collections.sort(mMediaBeanList, new Comparator<MediaInfo>() {
            @Override
            public int compare(MediaInfo file1, MediaInfo file2) {
                return Long.compare(file1.getDateModified(), file2.getDateModified());
            }
        });
        mDocumentsAdapter.notifyDataSetChanged();
    }

    // 根据文件大小排序
    public void sortBySize(List<MediaInfo> mMediaBeanList) {
        pos = 2;
        Collections.sort(mMediaBeanList, new Comparator<MediaInfo>() {
            @Override
            public int compare(MediaInfo file1, MediaInfo file2) {
                return Long.compare(file1.getSize(), file2.getSize());
            }
        });
        mDocumentsAdapter.notifyDataSetChanged();
    }


    private void initPopMenu() {
        mCirclePop = EasyPopup.create()
                .setContentView(this, R.layout.dialog_file_edit)
                //是否允许点击PopupWindow之外的地方消失
                .setFocusAndOutsideEnable(true)
                //背景变暗支持api>=18
//                .setBackgroundDimEnable(true)
                .apply();
        TextView tvSort = mCirclePop.findViewById(R.id.tvSort);
        TextView tvAddFile = mCirclePop.findViewById(R.id.tvAddFile);
        tvSort.setOnClickListener(v -> {
            mCirclePop.dismiss();
            mySortDialog.show();
        });
        tvAddFile.setOnClickListener(v -> {
            mCirclePop.dismiss();
            myAddDialog.show();
        });
    }

    //更多弹框
    private void moreDialog() {
        if (myMoreDialog == null) {
            myMoreDialog = new Dialog(mContext, R.style.DialogStyle);
        }
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_more, null);
        myMoreDialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = myMoreDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        lp.y = 0;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView ivIcon = inflate.findViewById(R.id.ivDialogMoreIcon);
        TextView tvName = inflate.findViewById(R.id.tvDialogMoreName);
        TextView tvDate = inflate.findViewById(R.id.tvDialogMoreDate);
        TextView tvSize = inflate.findViewById(R.id.tvDialogMoreSize);
        TextView tvCopy = inflate.findViewById(R.id.tvDialogMoreCopy);
        TextView tvInfo = inflate.findViewById(R.id.tvDialogMoreInfo);
        TextView tvRename = inflate.findViewById(R.id.tvDialogMoreRename);
        TextView tvDelete = inflate.findViewById(R.id.tvDialogMoreDelete);
        tvCopy.setOnClickListener(this);
        tvInfo.setOnClickListener(this);
        tvRename.setOnClickListener(this);
        tvDelete.setOnClickListener(this);
        getIcon(ivIcon);
        String phoneTime = TimeUtils.millis2String(FileUtils.getFileLastModified(mSelPath), "yyyy/MM/dd");
        tvName.setText(FileUtils.getFileName(mSelPath));
        tvDate.setText(phoneTime);
        tvSize.setText(Formatter.formatFileSize(mContext, new File(mSelPath).length()));
    }

    //信息弹框
    private void infoDialog() {
        if (myInfoDialog == null) {
            myInfoDialog = new Dialog(mContext, R.style.DialogStyle);
        }
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_info, null);
        myInfoDialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = myInfoDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        lp.y = 0;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView ivIcon = inflate.findViewById(R.id.ivDialogInfoIcon);
        TextView tvName = inflate.findViewById(R.id.tvDialogInfoName);
        TextView tvDate = inflate.findViewById(R.id.tvDialogInfoDate);
        TextView tvSize = inflate.findViewById(R.id.tvDialogInfoSize);
        TextView tvFileName = inflate.findViewById(R.id.tvDialogInfoFileName);
        TextView tvLocation = inflate.findViewById(R.id.tvDialogInfoLocation);
        TextView tvFileSize = inflate.findViewById(R.id.tvDialogInfoFileSize);
        TextView tvFileDate = inflate.findViewById(R.id.tvDialogInfoImportDate);
        getIcon(ivIcon);
        String phoneTime = TimeUtils.millis2String(FileUtils.getFileLastModified(mSelPath), "yyyy/MM/dd");
        tvName.setText(FileUtils.getFileName(mSelPath));
        tvDate.setText(phoneTime);
        tvSize.setText(Formatter.formatFileSize(mContext, new File(mSelPath).length()));
        tvFileName.setText(FileUtils.getFileName(mSelPath));
        tvLocation.setText(FileUtils.getDirName(mSelPath));
        tvFileSize.setText(FileUtils.getSize(mSelPath));
        tvFileDate.setText(TimeUtils.millis2String(FileUtils.getFileLastModified(mSelPath), getString(R.string.date_name)));
    }

    //重命名弹框
    private void renameDialog() {
        myRenameDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_rename, null);
        myRenameDialog.setContentView(inflate);
        myRenameDialog.setCancelable(true);
        Window dialogWindow = myRenameDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView cancel = inflate.findViewById(R.id.tvDialogRenameCancel);
        TextView comp = inflate.findViewById(R.id.tvDialogRenameConfirm);
        editRenameText = inflate.findViewById(R.id.etDialogRename);
        cancel.setOnClickListener(this);
        comp.setOnClickListener(this);
    }

    //添加文件夹弹框
    private void addDialog() {
        myAddDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_add, null);
        myAddDialog.setContentView(inflate);
        myAddDialog.setCancelable(true);
        Window dialogWindow = myAddDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView cancel = inflate.findViewById(R.id.tvDialogAddCancel);
        TextView comp = inflate.findViewById(R.id.tvDialogAddConfirm);
        editAddText = inflate.findViewById(R.id.etDialogAddName);
        cancel.setOnClickListener(this);
        comp.setOnClickListener(this);
    }

    //排序弹框
    private void sortDialog() {
        if (mySortDialog == null) {
            mySortDialog = new Dialog(mContext, R.style.DialogStyle);
        }
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_sort, null);
        mySortDialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = mySortDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        lp.y = 0;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView tvName = inflate.findViewById(R.id.tvDialogSortName);
        TextView tvTime = inflate.findViewById(R.id.tvDialogSortTime);
        TextView tvSize = inflate.findViewById(R.id.tvDialogSortSize);
        tvName.setOnClickListener(this);
        tvTime.setOnClickListener(this);
        tvSize.setOnClickListener(this);
    }

    private void getIcon(ImageView imageView) {
        if (FileUtils.isDir(mSelPath)) {
            imageView.setImageResource(R.drawable.awenjian);
        } else if (MimeUtils.isImgMimeType(mSelPath)) {
            imageView.setImageResource(R.drawable.atupian2);
        } else if (MimeUtils.isVideoMimeType(mSelPath)) {
            imageView.setImageResource(R.drawable.aship);
        } else if (MimeUtils.isAudioMimeType(mSelPath)) {
            imageView.setImageResource(R.drawable.ayinp);
        } else if (mSelPath.endsWith(".doc") || mSelPath.endsWith(".docx")) {
            imageView.setImageResource(R.drawable.adoc);
        } else if (mSelPath.endsWith(".xls") || mSelPath.endsWith(".xlsx")) {
            imageView.setImageResource(R.drawable.axcl);
        } else if (mSelPath.endsWith(".ppt") || mSelPath.endsWith(".pptx")) {
            imageView.setImageResource(R.drawable.appt);
        } else if (mSelPath.endsWith(".zip")) {
            imageView.setImageResource(R.drawable.ayasuobao);
        } else if (mSelPath.endsWith(".pdf")) {
            imageView.setImageResource(R.drawable.apdf);
        } else if (mSelPath.endsWith(".txt")) {
            imageView.setImageResource(R.drawable.atxt);
        } else {
            imageView.setImageResource(R.drawable.aweizhwenj);
        }
    }

}